﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Lyon.WinForm.NetMapSuite
{
    internal class NearestRect
    {
        static public bool RectangleContainsRectangle(Rectangle main, Rectangle current)
        {
            return main.Contains(current);
        }
        static public Rectangle GetNearestRect(Rectangle main, Rectangle current)
        {
            Point c1 = current.Location;
            Point c2 = new Point(current.Right, current.Top);
            Point c3 = new Point(current.Right, current.Bottom);
            Point c4 = new Point(current.Left, current.Bottom);

            if (!RectangleContainsPoint(main, c1))
            {
                c1 = GetNearestPoint(main, c1);
                current.Location = c1;
            }
            else if (!RectangleContainsPoint(main, c2))
            {
                c2 = GetNearestPoint(main, c2);
                current.Location = new Point(c2.X - current.Width, c2.Y);
            }
            else if (!RectangleContainsPoint(main, c3))
            {
                c3 = GetNearestPoint(main, c3);
                current.Location = new Point(c3.X - current.Width, c3.Y - current.Height);
            }
            else if (!RectangleContainsPoint(main, c4))
            {
                c4 = GetNearestPoint(main, c4);
                current.Location = new Point(c4.X, c4.Y - current.Height);
            }

            if (main.Contains(current))
                return current;
            else
                return GetNearestRect(main, current);
        }
        static public bool RectangleContainsPoint(Rectangle rect, Point point)
        {
            return (point.X >= rect.Left && point.X <= rect.Right)
                && (point.Y >= rect.Top && point.Y <= rect.Bottom);
        }
        static public Point GetNearestPoint(Rectangle rect, Point point)
        {
            if (point.X > rect.Right)
                point.X = rect.Right;
            else if (point.X < rect.Left)
                point.X = rect.Left;

            if (point.Y > rect.Bottom)
                point.Y = rect.Bottom;
            else if (point.Y < rect.Top)
                point.Y = rect.Top;

            return point;
        }
    }
}
